package order

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"ticket/utils"
)

func (o OrderApi) OrderList(ctx context.Context, req *OrderListReq) (res *OrderListRes, err error) {
	res = new(OrderListRes)
	// 获取当前登录用户信息
	userInfo, valid := utils.CurrentUserInfo(ctx)
	if !valid {
		return nil, utils.NewError("根据Token获取用户信息出错")
	}
	model := g.Model("orders")
	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 10
	}
	// 演出场次
	if req.PerformanceDate != nil && req.PerformanceTime != "" {
		model.Where("performances.performance_date", req.PerformanceDate).Where("performances.performance_time", req.PerformanceTime)
	}
	// 用户
	if req.Name != "" {
		model.Where("name like ?", "%"+req.Name+"%")
	}
	// 手机号
	if req.Phone != "" {
		model.Where("phone like ?", "%"+req.Phone+"%")
	}
	// 票状态
	if req.TicketStatus != 0 {
		model.Where("ticket_status", req.TicketStatus)
	}
	// 票类型
	if req.TicketType != 0 {
		model.Where("ticket_type", req.TicketType)
	}
	// 先查询订单基本信息
	err = model.Fields("orders.*, performance_date,performance_time").
		InnerJoin("performances on performances.id = orders.performance_id").
		Where("orders.agent_user_id = ?", userInfo.ID).
		Offset((req.Page - 1) * req.PageSize).Limit(req.PageSize).
		Scan(&res.List)
	if err != nil {
		return nil, utils.NewError("SQL出错了")
	}
	res.Total = len(res.List)
	return
}
